
from textual.widgets import Button, Static, Header, Footer
from textual.containers import ScrollableContainer
from textual.screen import Screen
from textual.reactive import reactive
from time import monotonic

class TimeDisplay(Static):
    '''A widget to display elapsed time'''

    start_time = reactive(monotonic)
    time = reactive(0.0)
    total = reactive(0.0)

    def on_mount(self) -> None:
        '''
        设置一个定时器，每隔一段时间调用 `update_time` 方法更新时间
        '''
        # self.set_interval(0.01, self.update_time)
        # 定时器
        self.update_timer = self.set_interval(1/25, self.update_time, pause=True)

    def update_time(self) -> None:
        # self.time = monotonic() - self.start_time
        self.time = self.total + (monotonic() - self.start_time)

    def watch_time(self, time: float) -> None:
        minutes, second = divmod(time, 60)
        hour, minutes = divmod(minutes, 60)
        self.update(f"{hour:02,.0f}:{minutes:02.0f}:{second:05.2f}")

    def start(self):
        '''唤醒计时器'''
        self.start_time = monotonic()   # 重新设置开始时间
        self.update_timer.resume()

    def stop(self):
        '''暂停计时器'''
        self.update_timer.pause()
        self.total += monotonic() - self.start_time  # 累加时间
        self.time = self.total

    def reset(self):
        '''重置计时器'''
        self.total = 0
        self.time = 0


class Stopwatch(Static):
    '''Stopwatch widget'''

    '''
    on_button_pressed 捕获按钮点击事件
    1. start 按钮开始计时，并添加一个 started 样式，表示计时已开始。
    2. stop 按钮暂停计时，并移除 started 样式，表示计时已停止。
    3. reset 按钮重置计时，将计时器重置为0。并根据按钮的ID执行相应的操作。

    '''
    def on_button_pressed(self, event: Button.Pressed) -> None:
        button_id = event.button.id
        time_display = self.query_one(TimeDisplay)
        if button_id == "start":
            time_display.start()
            self.add_class("started")
        elif button_id == "stop":
            time_display.stop()
            self.remove_class("started")
        elif button_id == "reset":
            time_display.reset()

    def compose(self):
        yield Button("Start", id="start", variant="success")
        yield Button("Stop",  id="stop", variant="error")
        yield Button("Reset", id="reset")
        yield TimeDisplay()

class StopwatchScreen(Screen):
    
    CSS_PATH = "stopwatch.tcss"

    def compose(self):
        yield Header()
        yield Footer()
        yield ScrollableContainer(Stopwatch(), Stopwatch(), Stopwatch())



if __name__ == "__main__":
    from textual.app import App
    from textual.binding import Binding
    class StopwatchApp(App):
        BINDINGS = [
            Binding("ctrl+q", "quit", "Quit"),
        ]

        def on_mount(self):
            self.push_screen(StopwatchScreen())
    
    StopwatchApp().run()
